package com.changgou.seckill.config;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class ConfirmMessageSender implements RabbitTemplate.ConfirmCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String MESSAGE_CONFIRM_KEY="message_confirm_";

    public ConfirmMessageSender(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setConfirmCallback(this);
    }

    @Override
    //接收消息服务器返回的通知方法
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if(ack){
            //删除redis中的相关数据
            redisTemplate.delete(MESSAGE_CONFIRM_KEY+correlationData.getId());
            redisTemplate.delete(correlationData.getId());//删除消息
        }else{
            //失败的通知
            Map<String,String> map = redisTemplate.opsForHash().entries(MESSAGE_CONFIRM_KEY + correlationData.getId());
            String exchange = map.get("exchange");
            String routineKey = map.get("routineKey");
            String message = map.get("message");
            rabbitTemplate.convertAndSend(exchange,routineKey,message);
        }
    }


    //自定义消息发送方法
    public void sendMessage(String exchange,String routineKey,String message){

        //设置消息的唯一标识 保存到redis中
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        redisTemplate.opsForValue().set(correlationData.getId(),message);

        Map<String,String > map = new HashMap<>();
        map.put("exchange",exchange);
        map.put("routineKey",routineKey);
        map.put("message",message);
        redisTemplate.opsForHash().putAll(MESSAGE_CONFIRM_KEY+correlationData.getId(),map);

        //携带唯一标识
        System.out.println("发送了一条消息： "+new Date());
        rabbitTemplate.convertAndSend(exchange,routineKey,message,correlationData);
    }

}
